<template>
    <div id="im">
        <div class="top">
            <div class="left" @click="router.go(-1)"><van-icon name="arrow-left" size="20px" />返回</div>
            <h3 style="margin-left: 120px">聊天信息</h3>
        </div>
        <el-col :span="6">
            <div class="chat-container">
                <div class="chat-room">
                    <el-scrollbar height="800px">
                        <div v-for="(item, index) in receiveMsgList" :key="index" class="message-item"
                            >
                            <div :class="{ 'message-self': item.fromUserId === currentUserId }" class="mes">
                                <img :src="item.avatar" alt="avatar" class="avatar" />
                                <div class="message-content">
                                    <span class="username">{{ item.username }}</span>
                                    <p class="content">{{ item.content }}</p>
                                </div>
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
                <div class="chat-input">
                    <el-input v-model="toSendMsg" style="width: 240px" :rows="1" type="textarea" placeholder="请输入内容" />
                    <el-button type="success" style="margin-left: 20px" @click="sendMsg">发送</el-button>
                </div>
            </div>
        </el-col>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { Msg } from "@/model"; // 导入定义的消息类
import { useRoute, useRouter } from "vue-router";
// 路由跳转
const router = useRouter();
// 获取当前用户数据并进行检查
const currentUserData = localStorage.getItem("user");
if (!currentUserData) {
    console.error("用户未登录，缺少用户数据");
    // 在这里可以选择跳转到登录页面或设置默认值
    // window.location.href = "/login"; // 如果需要重定向到登录页面
}

// 解析用户信息
const currentUser = currentUserData ? JSON.parse(currentUserData) : null;
const currentUserId = currentUser?._id || ""; // 当前用户 ID
const username = currentUser?.admin || "匿名用户"; // 用户名
const avatar = currentUser?.landlord || ""; // 头像

const route = useRoute();
const toUserId = route.query.id as string; // 接收者 ID
const toSendMsg = ref("");
const receiveMsgList = ref<Msg[]>([]);
const ws = new WebSocket('ws://localhost:3001');

// WebSocket 事件
onMounted(() => {
    if (currentUserId) {
        ws.addEventListener('open', () => {
            console.log("Connected to WebSocket server");
            ws.send(JSON.stringify({ type: 'register', userId: currentUserId }));
        });
    } else {
        console.error("缺少用户 ID，无法注册 WebSocket 连接");
    }
    ws.addEventListener('message', (event) => {
        const data = JSON.parse(event.data);
        receiveMsgList.value.push(data); // 添加接收到的消息
    });
    ws.addEventListener('close', () => {
        console.log("Disconnected from WebSocket server");
    });
    ws.addEventListener('error', (error) => {
        console.error("WebSocket error:", error);
    });
});

// 发送消息函数
function sendMsg() {
    if (!currentUserId) {
        console.error("缺少用户 ID，无法发送消息");
        return;
    }

    const msgInfo = {
        type: "chat",
        fromUserId: currentUserId,
        toUserId: toUserId,
        username: username,
        avatar: avatar,
        content: toSendMsg.value,
        timestamp: new Date()
    };

    receiveMsgList.value.push(msgInfo); // 立即显示发送的消息
    ws.send(JSON.stringify(msgInfo)); // 发送消息到服务器
    toSendMsg.value = ""; // 清空输入框
}
</script>

<style scoped lang="scss">
* {
    padding: 0;
    margin: 0;
}

#im {
    width: 100%;
    height: 100%;

    .top {
        width: 100%;
        height: 50px;
        background-color: #fff;
        display: flex;
        align-items: center;

        .left {
            padding-left: 10px;
        }
    }
}

.chat-container {
    width: 390px;
    height: 750px;
}

.chat-room {
    height: 100%;
}

.chat-input {
    height: 50px;
    width: 100%;
    position: absolute;
    bottom: 0;
    display: flex;
    align-items: center;
}

.message-item {
    display: flex;
    margin: 10px;
    text-align: left;
}
.mes{
    width: 100px;
}

.message-self {
    
    display: flex;
    flex-direction: row-reverse;
    /* 头像和消息框反转，靠右显示 */
    // justify-content: flex-end;
    margin-left: auto;
    /* 将消息项对齐到右侧 */
    text-align: right;
    /* 右侧消息文本右对齐 */
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin: 0 10px;
}

.message-content {
    background-color: #f0f0f0;
    width: 100px;
    padding: 10px;
    border-radius: 8px;
    max-width: 70%;
    text-align: left;
    /* 默认消息左对齐 */
}

.message-self .message-content {
    background-color: #cce5ff;
    /* 发送者的消息背景色不同 */
    text-align: right;
    /* 发送者消息内容右对齐 */
}

.username {
    font-weight: bold;
    margin-bottom: 5px;
}

.content {
    margin: 0;
}
</style>
